package CompletableFuture_14;

import java.util.concurrent.*;
import java.util.function.Supplier;

public class 多任务组合_allOf_anyOf
{
    public static void main(String[] args) throws Exception {
        ExecutorService executor = Executors.newFixedThreadPool(8);

        // 创建8个异步任务 - 使用Supplier
        CompletableFuture<String>[] futures = new CompletableFuture[8];
        for (int i = 0; i < 8; i++) {
            final int taskId = i;
            futures[i] = CompletableFuture.supplyAsync(new Supplier<String>() {
                public String get() {
                    try {
                        int sleepTime = 300 + taskId * 100;
                        Thread.sleep(sleepTime);
                        return "任务" + taskId + "(" + sleepTime + "ms)";
                    } catch (InterruptedException e) {
                        throw new RuntimeException(e);
                    }
                }
            }, executor);
        }

        // 等待所有任务完成
        CompletableFuture<Void> allDone = CompletableFuture.allOf(futures);
        allDone.thenRun(new Runnable() {
            public void run() {
                System.out.println("所有任务已完成");
                for (int i = 0; i < futures.length; i++) {
                    try {
                        System.out.println(futures[i].get());
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            }
        }).get();

        // 获取任意一个完成的任务
        CompletableFuture<Object> anyDone = CompletableFuture.anyOf(futures);
        anyDone.thenAccept(new java.util.function.Consumer<Object>() {
            public void accept(Object result) {
                System.out.println("第一个完成的任务: " + result);
            }
        }).get();

        executor.shutdown();
    }
}